<template>
  <div>
    <el-card class="search-card">
      <basic-table-form
        ref="formData"
        isScalingBtn
        :colNumOfRow="4"
        :formColumns="formItemList"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      >
      </basic-table-form>
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :pageSizes="pageSizes"
        :tableHeight="460"
        :showSelectCol="false"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <div slot="content_context">
          <el-button
            v-if="showBtn('导出')"
            :loading="exportLoading"
            type="primary"
            size="mini"
            icon="el-icon-download"
            @click="handleExportFile"
            >导出</el-button
          >
          <el-button
            v-if="showBtn('批量修改主供')"
            type="primary"
            size="mini"
            icon="el-icon-link"
            @click="$router.push({ name: 'batchModifyMainSupply' })"
          >批量修改主供</el-button>
          <el-button
            v-if="showBtn('批量修改到货周期')"
            type="primary"
            size="mini"
            icon="el-icon-link"
            @click="$router.push({ name: 'batchModifyArrivalTime' })"
          >批量修改到货周期</el-button>
        </div>
      </basic-table>
    </el-card>
  </div>
</template>
<script>
import BasicTableForm from '@/components/BasicForm';
import BasicTable from '@/components/BasicTable';
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
import { getSearchParamBySearchType } from '@/utils/getUtils';
import { isResponseSuccess, createExcelByExport } from '@/utils/bizUtils';
import {
  FORM_ITEM_LIST,
  IS_MAINSUPPLY_OPTIONS,
} from './constants';

export default {
  components: {
    BasicTableForm,
    BasicTable
  },
  data () {
    return {
      exportLoading: false,
      formItemList: FORM_ITEM_LIST,
      tableInfo: {
        list: [],
        columns: [
          {
            title: '供应商代码',
            key: 'supplyUuid',
            width: 90
          },
          {
            title: '供应商名称',
            key: 'supplyName',
            render: (h, { row }) => {
              if (row.supplyInfoDTO) {
                return <span>{row.supplyInfoDTO.supplyName}</span>
              }
            }
          },
          {
            title: '供应商主营品类',
            key: 'supplyCategoryName',
            render: (h, { row }) => {
              if (row.supplyInfoDTO) {
                return <span>{row.supplyInfoDTO.supplyCategoryName}</span>
              }
            }
          },
          {
            title: '供应商管理区域',
            key: 'supplyManagerArea',
            render: (h, { row }) => {
              if (row.supplyInfoDTO) {
                return <span>{row.supplyInfoDTO.supplyManagerArea}</span>
              }
            }
          },
          // 1是 2 否
          {
            title: '是否敏感商品',
            key: 'isPriceSensitive',
            render: (h, { row }) => {
              if (row.supplyProductInfo) {
                return <span>{row.supplyProductInfo.isPriceSensitive == 1 ? '是' : '否' }</span>
              }
            }
          },
          {
            title: '商品管理区域',
            key: 'manageArea',
            render: (h, { row }) => {
              if (row.supplyProductInfo) {
                return <span>{row.supplyProductInfo.manageArea}</span>
              }
            }
          },
          {
            title: '业务区域',
            key: 'saleAreaName'
          },
          {
            title: '销售省',
            key: 'saleProvinceName'
          },
          {
            title: '城市',
            key: 'saleCityName'
          },
          {
            title: 'SPU编码',
            key: 'spuNo'
          },
          {
            title: 'SKU编码',
            key: 'skuNo'
          },
          {
            title: '商品名称',
            key: 'productName'
          },
          {
            title: '规格',
            key: 'specDetailStr',
            render: (h, { row }) => {
              if (row.supplyProductInfo) {
                return <span>{row.supplyProductInfo.specDetailStr}</span>
              }
            }
          },
          {
            title: '主计量单位',
            key: 'supplyGoodsUnit',
            width: 90,
            render: (h, { row }) => {
              if (row.supplyProductInfo) {
                return <span>{row.supplyProductInfo.supplyGoodsUnit}</span>
              }
            }
          },
          {
            title: '商品供货状态',
            key: 'supplyGoodsState',
          },
          {
            title: '是否主供',
            key: 'isMainSupply',
            width: 90,
            render: (h, { row }) => {
              if (row.mainSupply != 1) {
                return <el-select size='mini' v-model={row.isMainSupply}>
                  {
                    IS_MAINSUPPLY_OPTIONS.map(item => {
                      return (
                        <el-option key={item.value} value={item.value} label={item.label}/>
                      )
                    })
                  }
                </el-select>
              }
              return <span>是</span>
            }
          },
          {
            title: '到货周期',
            key: 'arrivalDays',
            width: 90
          },
          {
            title: '合同到货周期',
            key: 'supplycycle',
            render: (h, { row }) => {
              if (row.supplyInfoDTO) {
                return <span>{row.supplyInfoDTO.supplycycle}</span>
              }
            }
          },
        ],
        loading: false
      },
      pagination: {
        nowPage: 1,
        totalNum: 0,
        pageShow: 10
      },
      pageSizes: [10, 20, 30, 40],
      formData: {
        spuNo: '',
        skuNo: '',
        productName: '',
        isMainSupply: '',
        saleAreaName: '',
        saleProvinceName: '',
        supplyUuid: '',
        supplierName: '',
      },
      apiObj: {
        // 获取列表数据
        baseQueryList: {
          url: '/sysback/supplyarea/getProductPager?isForStopSupply=false',
          type: 'post'
        },
        // 提交
        batchUpdateRel: {
          url: '/sysback/supplyarea/updateSupplyAreaOrArrivalDay',
          type: 'post'
        },
        // 提交
        exportFileService: {
          url: '/sysback/supplyarea/exportExcel?isForStopSupply=false',
          type: 'post'
        }
      }
    };
  },
  created () {
    // this.initData();
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  methods: {
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      return <div class="table-action">
        <el-button type="text" onClick={() => this.submit(row)}>提交</el-button>
      </div>;
    },
    // 获取表单内容
    getFormData (data) {
      this.formData = data;
    },
    // 表单查询
    handleQueryForm () {
      this.pagination.nowPage = 1;
      this.getTableData();
    },
    // 页码切换
    handlePageChange (val) {
      this.pagination.nowPage = val;
      this.getTableData();
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.pagination.pageShow = val;
      this.getTableData();
    },
    getTableData () {
      let data = {
        searchParam: JSON.stringify(getSearchParamBySearchType(FORM_ITEM_LIST, this.formData)),
        ...this.pagination
      };
      const curBtnId = getBtnsId('查询');
      sessionStorage.setItem('buttonId', curBtnId);
      this.tableInfo.loading = true;
      ApiRequest(
        this.apiObj.baseQueryList.url,
        this.apiObj.baseQueryList.type,
        data
      ).then((res) => {
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          const { results, totalNum } = res.retData;
          results.forEach((item) => {
            item.mainSupply = item.isMainSupply;
          });
          this.tableInfo.list = results;
          this.pagination.totalNum = totalNum;
        }
      });
    },
    // 提交数据
    submit (row) {
      this.tableInfo.loading = true;
      let curBtnId = getBtnsId('提交');
      sessionStorage.setItem('buttonId', curBtnId);
      ApiRequest(
        this.apiObj.batchUpdateRel.url,
        this.apiObj.batchUpdateRel.type,
        row
      )
        .then((res) => {
          if (isResponseSuccess(res)) {
            this.$message.success('提交成功');
            this.getTableData();
          }
          this.tableInfo.loading = false;
        })
        .catch(() => {
          this.tableInfo.loading = false;
        });
    },
    // 导出
    handleExportFile () {
      let data = {
        searchParam: JSON.stringify(getSearchParamBySearchType(FORM_ITEM_LIST, this.formData)),
      };
      const curBtnId = getBtnsId('查询');
      sessionStorage.setItem('buttonId', curBtnId);
      this.exportLoading = true;
      ApiRequestExportTable(
        this.apiObj.exportFileService.url,
        this.apiObj.exportFileService.type,
        data
      )
        .then((res) => {
          this.exportLoading = false;
          if (res) {
            createExcelByExport({ excelTitle: '主供及到货周期', res });
          }
        })
        .catch(() => {
          this.exportLoading = false;
          this.$message.error('导出失败');
        });
    },
  }
};
</script>
